<style lang="less">
.login-form {
  margin: 0 auto;
  width: 80%;
  padding-top: 150px;
}
</style>

<template>
  <nut-navbar title="登录" left-show @click-back="router.back" />
  <div class="login-form">
    <nut-form ref="loginFormRef" :model-value="form" :rules="rules">
      <nut-form-item>
        <nut-input v-model="form.username" placeholder="请输入用户名" type="text" clearable>
          <template #left><My /></template>
        </nut-input>
      </nut-form-item>
      <nut-form-item>
        <nut-input v-model="form.password" placeholder="请输入密码" type="password" clearable>
          <template #left><Setting /></template>
        </nut-input>
      </nut-form-item>
      <nut-form-item>
        <nut-row>
          <nut-col :span="12">
            <nut-input v-model="form.code" placeholder="请输入验证码" type="text" clearable />
          </nut-col>
          <nut-col :span="12">
            <img
              :src="store.captcha"
              style="width: 100%"
              @click="store.refreshCaptcha"
              v-if="store.captcha !== ''"
            />
          </nut-col>
        </nut-row>
      </nut-form-item>
      <nut-form-item>
        <nut-row :gutter="10">
          <nut-col :span="12" style="text-align: center">
            <nut-button type="primary" @click="handleLogin">登录</nut-button>
          </nut-col>
          <nut-col :span="12" style="text-align: center">
            <nut-button type="default" @click="handleRegister">注册</nut-button>
          </nut-col>
        </nut-row>
      </nut-form-item>
    </nut-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import type { LoginForm } from '@/config/form'
import { My, Setting } from '@nutui/icons-vue'

const store = useAuthStore()
const route = useRoute()
const router = useRouter()
const form = ref<LoginForm>({
  username: '',
  password: '',
  code: ''
})
const loginFormRef = ref()
const rules = {
  username: [{ required: true, message: '请填写用户名' }],
  password: [{ required: true, message: '请填写密码' }],
  code: [{ required: true, message: '请填写验证码' }]
}

onMounted(() => store.refreshCaptcha())

const handleLogin = () => {
  loginFormRef.value.validate().then(async ({ valid, errors }) => {
    if (valid) {
      await store.login(form.value)
      if (store.isLoggedIn) {
        const redirect = route.query.redirect
        if (redirect) {
          router.push({ path: redirect || '/' })
        } else {
          router.push({ name: 'my' })
        }
      }
    }
  })
}

const handleRegister = () => {
  router.push({ name: 'register' })
}
</script>
